<template></template>

<script setup lang="ts">
import * as L from 'leaflet'
import type { IPixelLayerStyleOptions } from '@quickearth/core'
import {
  resourceService,
  getText,
  MicapsDiamond4GridDataProvider
} from '@quickearth/core'
import { LGridLabelLayer, LPixelLayer } from '@quickearth/leaflet'
import apiList from '@/pages/integrated-monitoring/api/api'
import { useMonitoringStore } from '@/pages/integrated-monitoring/store/store'
const centerApi = import.meta.env.VITE_BASE_URL
const monitoringStore = useMonitoringStore()

const gdskjcCurrentSelect = computed(() => monitoringStore.gdskjcCurrentSelect)
const gdskjcDataList = computed(() => monitoringStore.gdskjcDataList)
const sbGdCurrentSelect = computed(() => monitoringStore.sbGdCurrentSelect)
const baseMap = inject('baseMap')
let labelLayer
const layers = L.layerGroup().addTo(toRaw(baseMap.value))
async function updateGridLayer(type, styleType) {
  const res = await apiList.getChoroplethicMapPath({
    elementCode: gdskjcCurrentSelect.value
  })
  if (!res.data) return
  await resourceService.loadResourceFromConfigPath(
    'demos/styles/demo.config.json'
  )
  const labelStyle = {
    text: {
      data: '#decimal',
      offset: [0, 15]
    }
  }
  let newList = res.data.url.split(',')
  text = await getText(centerApi + newList[2])
  let provider = new MicapsDiamond4GridDataProvider(Buffer)
  labelLayer = new LGridLabelLayer()
    .setDataSource(provider)
    .setDrawOptions(labelStyle)
  layers.addLayer(labelLayer)
  monitoringStore.mapLoading = false
}

const handleShowLayer = type => {
  layers.clearLayers()
  const currentSelect = monitoringStore.gdskjcOptions.find(
    i => i.value === gdskjcCurrentSelect.value
  )
  if (currentSelect) {
    updateGridLayer(type, currentSelect.legendStyle)
  }
}
useEventBus('handleShowGridPointMonitoringLayer').on(handleShowLayer)
watch(
  () => gdskjcCurrentSelect.value,
  val => {
    if (val !== 'none') {
      handleShowLayer(val)
    } else {
      layers.clearLayers()
    }
  },
  {
    deep: true
  }
)
watch(
  () => sbGdCurrentSelect.value,
  val => {
    if (gdskjcCurrentSelect.value !== 'none') {
      handleShowLayer(gdskjcCurrentSelect.value)
    } else {
      layers.clearLayers()
    }
  },
  {
    deep: true
  }
)
onMounted(() => {
  if (layers) layers.clearLayers()
  if (gdskjcCurrentSelect.value !== 'none') {
    handleShowLayer(gdskjcCurrentSelect.value)
  }
})
onUnmounted(() => {
  layers.clearLayers()
})
</script>

<style scoped lang="scss"></style>
